package com.syx.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.syx.entity.Car;
import com.syx.service.CarService;
import com.syx.util.FileUploadUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class CarController {
    @Resource
    private CarService carService;

    @RequestMapping("list.do")
    public String carList(Model model,
                          String cname,
                          String priceMin,
                          String priceMax,
                          @RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum){
        PageHelper.startPage(pageNum,3);
        Map map = new HashMap();
        map.put("cname",cname);
        map.put("priceMin",priceMin);
        map.put("priceMax",priceMax);
        List list = carService.carList(map);
        PageInfo pageInfo = new PageInfo(list);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("map",map);
        return "list";
    }

    @RequestMapping("addTo.do")
    public String addTo(){
        return "add";
    }

    @RequestMapping("typeList.do")
    @ResponseBody
    public Object typeList(){
        List list = carService.typeList();
        return list;
    }

    @RequestMapping("del.do")
    @ResponseBody
    public Object del(Integer cid){
        int i = carService.del(cid);
        return i;
    }

    //typeList.do

    @RequestMapping("add.do")
    @ResponseBody
    public Object typeList(Car car, HttpSession session, MultipartFile photo){
        if (photo.getSize()>0){
            String upload = FileUploadUtil.load(session, photo, "upload");
            car.setPic(upload);
        }
        int i = carService.add(car);
        return i;
    }
}
